import React, { Component } from 'react'
import { connect } from 'react-redux'
import DataHoc from "containers/pay/template/data-hoc";
import { Alert, Button, message, Popconfirm, Radio, Spin, Modal } from "antd";
import { messages } from "share/common";
import AdvancedTable from "components/advanced-table";
import PayModal from "../unpaid/pay-modal";
import paymentService from "../pay-workbench.service";
import BankHoc from "../../template/bank-hoc";
import Space from "components/space";
import { orderTab, optionsMap, handleOptions } from "../../template/utils"

class Fail extends Component {

  key = 'Fail';

  state = {
    loading: false,
    tableTitle: [],
    rowSelection: this.props.getSelection(this.props.noticeAlert)(true),
    selectedData: [],
    buttonDisabled: true,
    radioValue: '',
    radioOption: [],
    setOfBookId : '',
    visible: false,
    searchForm: this.props.getSearchForm(this.key),
    searchParams: {},
    bankInfo: undefined,
    sortDTOs: []
  };

  componentWillMount = () => {
    const { setOfBooksId } = this.props.company;
    this.setState({ loading: true });
    paymentService.getOptions({ setOfBookId: setOfBooksId }).then(res => {
      let radioValue = optionsMap.get(res.data.defPaymentMethods[0]).itemCode;
      this.setState({
        loading: false,
        radioOption: orderTab(handleOptions(res.data.ablePaymentMethods)),
        radioValue,
        setOfBookId: setOfBooksId
      })
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    })
  };

  service = (page, pageSize, searchParams) => {
    let { radioValue, setOfBookId, bankInfo, sortDTOs } = this.state, { initConfig } = this.props;
    let params = {
      page, size: pageSize, paymentMethodCategory: radioValue, ...searchParams,
      sortProperty: (sortDTOs[0] || {}).property,
      sortDirection: (sortDTOs[0] || {}).direction
    };
    !params.paymentCompanyId && bankInfo && (params.paymentCompanyId = (bankInfo.paymentAuthCompanyIds || null));
    !params.currencyCode && bankInfo && bankInfo.companyBank && !bankInfo.companyBank.multiCurrencyPay && (params.currencyCode = bankInfo.companyBank.currencyCode);
    return initConfig(this.key, params, searchParams.setOfBookId !== setOfBookId ? searchParams.setOfBookId : '');
  };

  onRadioChange = e => {
    this.setState({ radioValue: e.target.value }, () => {
      this.advancedTableRef.setState({
        pagination: Object.assign(this.advancedTableRef.state.pagination, { current: 1 })
      });
      this.selectorRef.handleFocus();
    });
  };

  handleOk = () => {
    this.setState({ visible: false }, this.handleRefresh);
  };

  handleCancelPay = () => {
    const { selectedData } = this.state;
    this.setState({ loading: true });
    paymentService.cancelPay(selectedData).then(() => {
      this.setState({ loading: false });
      this.handleOk();
    }).catch(() => {
      this.setState({ loading: false });
      message.error(messages('finance-4.key111')/*取消支付失败，请重试*/);
    })
  };

  onSearch = (pagination, values) => {
    setTimeout(() => {
      this.setState({ searchParams: values }, () => {
        this.props.onClearSelected(() => this.props.noticeAlert([]));
        this.selectorRef.handleFocus();
      });
    }, 0);
  };

  handleChangeBank = value => {
    this.setState({ bankInfo: value }, this.handleRefresh);
  };

  handleRefresh = () => {
    this.props.onClearSelected(() => this.props.noticeAlert([]));
    this.advancedTableRef.getList();
  };

  handlePay = () => {
    const { bankInfo, selectedData } = this.state;
    if (!bankInfo) {
      message.error(messages('finance-4.key112')/*不存在有权限的付款账户，无法执行该操作，请确认公司账户授权配置*/);
      return -1;
    }
    if (bankInfo.accountType === 'BANKCARD_ACCOUNT'
      && selectedData.filter(item => item.accountType === 'ALIPAY_LOGON_ID').length) {
      Modal.error({
        title: messages('finance-4.key113')/*所选行中有收款账户为支付宝账户的数据，请返回检查后再确认支付*/
      });
      return -1;
    }
    let flag = true;
    selectedData.every(item => {
      if (item.currency !== selectedData[0].currency) {
        flag = item.currency === selectedData[0].currency;
        return true;
      }
      return false;
    });
    if (!flag) {
      Modal.error({
        title: messages('finance-4.key416')/*不允许跨币种组批，请重新选择付款数据。*/
      });
      return -1;
    }
    this.setState({ visible: true });
  };

  getColumns = () => {
    const { getColumns } = this.props;
    return getColumns(this.key).concat([{
      title: messages('common.operation')/*操作*/, dataIndex: 'operate', fixed: 'right',
      render: (value, record) => record.ledgerStatus === 'F' ?
        <a onClick={() => this.handleReLedger(record)}>{messages('finance-4.key114')/*重新生成凭证*/}</a> : '-'
    }])
  };

  handleReLedger = record => {
    paymentService.reLedger([record.id]).then(() => {
      message.success(messages('common.operate.success')/*操作成功*/);
      this.advancedTableRef.getList()
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  render() {
    const { handleTableTitle, handleTableChange } = this.props;
    const { loading, tableTitle, rowSelection, buttonDisabled, radioValue, radioOption,
      errorAlert, visible, selectedData, searchForm, searchParams, bankInfo, setOfBookId } = this.state;
    return (
      <div style={{ height: '100%' }}>
        <Spin spinning={loading}>
          <AdvancedTable
            title={messages('finance-4.key115')/*退票或失败*/}
            tableName='pay-Fail'
            service={this.service}
            onChange={handleTableChange}
            tableTitle={() => handleTableTitle(tableTitle, selectedData, true)}
            onRef={ref => this.advancedTableRef = ref}
            searchForm={searchForm}
            rowKey="id"
            searchNotGetList
            pagination={{
              pageSizeOptions: ['20', '50', '100', '150', '200', '500']
            }}
            rowSelection={rowSelection}
            columns={this.getColumns()}
            onSearch={this.onSearch}
            footer={
              <Space>
                <Button type="primary" disabled={buttonDisabled} onClick={this.handlePay}>
                  {messages('finance-4.key116')/*重新支付*/}
                </Button>
                <Popconfirm title={messages('finance-4.key117')/*确定取消支付吗*/} onConfirm={this.handleCancelPay}>
                  <Button type="primary" disabled={buttonDisabled}>{messages('finance-4.key93')/*取消支付*/}</Button>
                </Popconfirm>
              </Space>
            }
          >
            <Radio.Group value={radioValue} style={{ marginBottom: '12px' }}
                         onChange={this.onRadioChange}>
              {
                radioOption.map(item => <Radio.Button value={item.itemCode}>{item.showName}</Radio.Button>)
              }
            </Radio.Group>
            <BankHoc
              searchParams={searchParams}
              radioValue={radioValue}
              onRef={ref => this.selectorRef = ref}
              onChangeBank={this.handleChangeBank}
            />
            <div style={{ margin: '12px 0' }}>
              { errorAlert && <Alert message={errorAlert} type="error" showIcon style={{ width: '100%' }}/> }
            </div>
          </AdvancedTable>
          <PayModal
            radioValue={radioValue}
            visible={visible}
            onCancel={() => { this.setState({ visible: false }) }}
            record={selectedData}
            mode={'Fail'}
            setOfBookId={setOfBookId}
            onOk={this.handleOk}
            bankInfo={bankInfo}
          />
        </Spin>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default connect(mapStateToProps)(DataHoc(Fail));
